package com.example.bookstore.beans;

import javax.faces.FacesException;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;

import com.example.bookstore.cart.ShoppingCart;
import com.example.bookstore.entity.Book;
import com.example.bookstore.exception.BookNotFoundException;

@ManagedBean(name = "store")
public class BookstoreBean extends BaseBean {

	private Book featured = null;

	public String add() {
		System.out.println("BookstoreBean: add");
		Book featured = getFeatured();
		String bookId = featured.getBookId();
		ShoppingCart cart = shoppingCart();
		cart.add(bookId, featured);

		return "cart";
	}

	@Override
	public String details() {
		FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
				.put("selected", getFeatured());

		return "details";
	}

	public Book getFeatured() {
		if (featured == null) {
			try {
				// TODO: Replace 203 with random book
				featured = bookController().getBook("203");
				getSessionMap().put("selected", featured);
			} catch (BookNotFoundException e) {
				throw new FacesException("Could Not Get Book Details "
						+ e.getMessage());
			}
		}

		return featured;
	}
}
